import React, { PureComponent, Fragment } from 'react';
import { connect,routerRedux } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Table,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../../../layouts/PageHeaderLayout'
import styles from '../../TableList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
/**
 * @param
 * 字段类型：文本0 引用1 单选2
 * 是否必填：是1 否0
 * 启用状态：是1 否0
 * 是否可编辑：是1 否0
 */
const optionArr = {
  type:[
    {
      id:'0',
      label:'文本'
    },
    {
      id:'1',
      label:'引用'
    },
    {
      id:'2',
      label:'单选'
    }
  ],
  yesno:[
    {
      id:'0',
      label:'否'
    },
    {
      id:'1',
      label:'是'
    }
  ]
}

const buildOption = (name)=>{
  const typeOption =
    optionArr[name].map(type => (
      <Option key={type.id} value={type.id}>
        {type.label}
      </Option>
    ))
  return typeOption;
}

//弹出框
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,modalType,modalItem } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title={modalType}//编辑 modeltype
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="No.字段标识">
         {form.getFieldDecorator('id', {
           initialValue: modalItem.id,
           rules: [{ required: true }],
         })(<Input placeholder="请输入" />)}
       </FormItem>
     </Row>
     <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="字段名称">
         {form.getFieldDecorator('name', {
           initialValue: modalItem.name,
           rules: [{ required: true }],
         })(<Input placeholder="请输入" />)}
       </FormItem>
     </Row>
     <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="字段类型">
         {form.getFieldDecorator('type', {
           initialValue: modalItem.type,
           rules: [{ required: true}],
         })(
            <Select style={{ width: '100%' }}>{buildOption('type')}</Select>
          )}
       </FormItem>
     </Row>
     <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="是否必填">
         {form.getFieldDecorator('required', {
           initialValue: modalItem.required,
           //rules: [{ required: true}],
         })(
            <Select style={{ width: '100%' }}>{buildOption('yesno')}</Select>
         )}
       </FormItem>
     </Row>
     <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="启用状态">
         {form.getFieldDecorator('status', {
           initialValue: modalItem.status,
           //rules: [{ required: true}],
         })(
            <Select style={{ width: '100%' }}>{buildOption('yesno')}</Select>
         )}
       </FormItem>
     </Row>
     <Row>
       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="备注">
         {form.getFieldDecorator('memo', {
           initialValue: modalItem.memo,
           //rules: [{ required: true}],
         })(<Input placeholder="请输入" />)}
       </FormItem>
     </Row>
    </Modal>
  );
});

@connect(({ sysdic, loading }) => ({
  sysdic,
  loading: loading.models.sysdic,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    modalType:'新增',// 编辑还是删除
    modalItem:{}, // 当前编辑行的值
    pageTitle:null,
    id:null//上页传来的id
  };

  componentDidMount() {
    const { dispatch,location } = this.props;
    this.setState({
      pageTitle:"数据字典-" + location.query.pageTitle,
      id:location.query.id,
    })
    //根据拿到的id向后端查询数据
    dispatch({
      type: 'sysdic/fetchdetail',
      payload:{
        id:location.query.id
      }
    });
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysdic/clear',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    /**
     * @desc 这是啥函数...
     */
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysdic/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'sysdic/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'sysdic/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  //筛选
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'sysdic/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  //新增
  handleAdd = (fields) => {
    this.props.dispatch({
      type: 'sysdic/adddetail',
      payload: {
        data:{
          ...fields
        },
        pid:this.state.id,
        type:this.state.modalType//新增还是修改
      },
    });
    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  handleToAdd = record =>{
    this.setState({
      modalVisible: true,
      modalItem: {},
      modalType:'新增字段'
    });
  }
  handleToEdit = record =>{
    this.setState({
      modalVisible: true,
      modalItem: record,
      modalType:'编辑字段'
    });
  }

  render() {
    const {sysdic:{data},loading } = this.props;
    const { selectedRows, modalVisible,modalType,modalItem } = this.state;

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const modalProps = {
      handleAdd: this.handleAdd,
      //handleEdit:this.handleEdit,
      handleModalVisible: this.handleModalVisible,
      modalItem:modalItem,
      modalType:modalType,
      modalVisible:modalVisible
    };

    const columns =
    [
      {
        title: 'No.字段标识',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '字段名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '字段类型',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: '是否必填',
        dataIndex: 'required',
        key: 'required',
      },
      {
        title: '启用状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '备注',
        dataIndex: 'memo',
        key: 'memo',
      },
      {
        title: '操作',
        render: (text,record) => (
          <Fragment>
            <a onClick={()=>this.handleToEdit(record)}>编辑</a>
            <Divider type="vertical" />
            <a >作废</a>
          </Fragment>
        ),
      },
    ]

    return (
      <PageHeaderLayout title={this.state.pageTitle}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleToAdd(true)}>
                添加字段
              </Button>
              {
                selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...modalProps}  />
      </PageHeaderLayout>
    );
  }
}
